//
//  DXHomeViewModel.swift
//  新浪微博
//
//  Created by dix on 2017/2/6.
//  Copyright © 2017年 dix. All rights reserved.
//

import UIKit
import SDWebImage
/*
    - 作用: 
        - 帮助HomeVC 请求数据
        - 给HomeVC 提供数据
 
 */
class DXHomeViewModel: NSObject {
    //保存首页数据的数组
    lazy var dataArr: [DXStatusViewModel] = [DXStatusViewModel]()
}
extension DXHomeViewModel{
    func getHomeData(isFinish:@escaping (Bool)->()){
        //请求数据
        DXNetworkTools.shared.loadHomeData(success: { (response) in
            guard let resDict = response as? [String: Any] else {
                //执行闭包
                isFinish(false)
                return
            }
            guard let res = resDict["statuses"] else {
                //执行闭包
                isFinish(false)
                return
            }
            //得到的模型数组
            let statusArray = NSArray.yy_modelArray(with: DXHomeModel.self, json: res) as! [DXHomeModel]
            // 创建一个临时可以可变的数组-> [DXStatusViewModel]
            var tempArr: [DXStatusViewModel] = [DXStatusViewModel]()
            //创建调度组
            let group = DispatchGroup()
            // 遍历statusArray 创建statuViewModel 然后对齐身上的homeModel进行赋值 然后 保存到临时数组中
            for homeModel in statusArray{
                //判断是否是原创微博
                if homeModel.pic_urls?.count == 1 {
                    group.enter()
                    //使用SDWebImage
                    SDWebImageManager.shared().downloadImage(with: URL(string: homeModel.pic_urls?.first?.thumbnail_pic ?? ""), options: [], progress: nil, completed: { (image, error, _, _, _) in
                        group.leave()
                    })
                }
                //判断是否是转发微博
                if homeModel.retweeted_status?.pic_urls?.count == 1 {
                    group.enter()
                    //使用SDWebImage
                    SDWebImageManager.shared().downloadImage(with: URL(string: homeModel.retweeted_status?.pic_urls?.first?.thumbnail_pic ?? ""), options: [], progress: nil, completed: { (image, error, _, _, _) in
                        group.leave()
                    })
                
                
                }
                let statusViewModel = DXStatusViewModel()
                //对属性赋值
                statusViewModel.homeModel = homeModel
                //添加数组临时数组中
                tempArr.append(statusViewModel)
            }
            self.dataArr = tempArr
            group.notify(queue: DispatchQueue.main, execute: { 
                //执行闭包
                isFinish(true)

            })

        }, failure: {(error)->() in
            //执行闭包
            isFinish(false)
            
        })

    
    }

}
